package com.ruoyi.washer.service.impl;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.washer.common.WxWechatTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.washer.mapper.XwDeviceMapper;
import com.ruoyi.washer.domain.XwDevice;
import com.ruoyi.washer.service.IXwDeviceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author hawking
 * @date 2023-12-15
 */
@Service
public class XwDeviceServiceImpl implements IXwDeviceService
{
    @Autowired
    private XwDeviceMapper xwDeviceMapper;
    @Autowired
    private WxWechatTools wxWechatTools;

    /**
     * 查询设备管理
     *
     * @param deviceId 设备管理主键
     * @return 设备管理
     */
    @Override
    public XwDevice selectXwDeviceByDeviceId(Long deviceId)
    {
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceId(deviceId);
        if(xwDevice.getSalesGrid()!=null){
            xwDevice.setSalesGrid01(JSONArray.parseArray(xwDevice.getSalesGrid()));
        }
        if(xwDevice.getRentGrid()!=null){
            xwDevice.setRentGrid01(JSONArray.parseArray(xwDevice.getRentGrid()));
        }
        if(xwDevice.getStopGrid()!=null){
            xwDevice.setStopGrid01(JSONArray.parseArray(xwDevice.getStopGrid()));
        }
        return xwDevice;
    }

    /**
     * 查询设备管理列表
     *
     * @param xwDevice 设备管理
     * @return 设备管理
     */
    @Override
    public List<XwDevice> selectXwDeviceList(XwDevice xwDevice)
    {
        /*
        List<XwDevice> xwDeviceList=xwDeviceMapper.selectXwDeviceList(xwDevice);
        List<XwDevice> list=new ArrayList<XwDevice>();
        for(int i=0;i<xwDeviceList.size();i++){
            XwDevice xwDevice1=xwDeviceList.get(i);
            if(xwDevice1.getSalesGrid()!=null){
                xwDevice1.setSalesGrid01(JSONArray.parseArray(xwDevice1.getSalesGrid()));
            }
            if(xwDevice1.getRentGrid()!=null){
                xwDevice1.setRentGrid01(JSONArray.parseArray(xwDevice1.getRentGrid()));
            }
            if(xwDevice1.getStopGrid()!=null){
                xwDevice1.setStopGrid01(JSONArray.parseArray(xwDevice1.getStopGrid()));
            }
            list.add(xwDevice1);
        }
        *
         */
        return xwDeviceMapper.selectXwDeviceList(xwDevice);
    }

    /**
     * 新增设备管理
     *
     * @param xwDevice 设备管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertXwDevice(XwDevice xwDevice)
    {
        Integer deviceCount=xwDevice.getDeviceCount();
        for(int i=1;i<=deviceCount;i++){
            xwDeviceMapper.insertXwDevice(xwDevice);
            xwDevice.setDeviceSn(xwDevice.getDeviceType()+xwDevice.getDeviceId());
            xwDeviceMapper.updateXwDevice(xwDevice);
            xwDevice.setDeviceId(null);
        }
        return 1;
    }

    /**
     * 修改设备管理
     *
     * @param xwDevice 设备管理
     * @return 结果
     */
    @Override
    public int updateXwDevice(XwDevice xwDevice)
    {
        return xwDeviceMapper.updateXwDevice(xwDevice);
    }

    /**
     * 批量删除设备管理
     *
     * @param deviceIds 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteXwDeviceByDeviceIds(Long[] deviceIds)
    {
        return xwDeviceMapper.deleteXwDeviceByDeviceIds(deviceIds);
    }

    /**
     * 删除设备管理信息
     *
     * @param deviceId 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteXwDeviceByDeviceId(Long deviceId)
    {
        return xwDeviceMapper.deleteXwDeviceByDeviceId(deviceId);
    }

   @Transactional
   public int  saveDevice(String openId,String deviceSn,String type){
       XwDevice xwDevice=new XwDevice();
       xwDevice.setDeviceSn(deviceSn);
       XwDevice xwDevice1=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
       if(xwDevice1==null){//系统找不到对应的设备
           return 0;
       }
        if(type.equals("1")){//代理商入库设备
           String openId1=xwDevice1.getAgentOpenId();
           if(openId1!=null&&openId1.equals(openId)){
               return 1;
           }else if(openId1!=null&&openId1.trim().length()>5){
               return 2;
           }else{
               xwDevice1.setAgentOpenId(openId);
               xwDevice1.setAgentTime(new Date());
               xwDeviceMapper.updateXwDevice(xwDevice1);
               return 3;
           }

        }else{//终端入库设备
            String openId1=xwDevice1.getEnduserOpenId();
            if(openId1!=null&&openId1.equals(openId)){
                return 1;
            }else if(openId1!=null&&openId1.trim().length()>5){
                return 2;
            }else{
                xwDevice1.setEnduserOpenId(openId);
                xwDevice1.setEnduserTime(new Date());
                xwDeviceMapper.updateXwDevice(xwDevice1);
                return 3;
            }
        }
    }
    public XwDevice getDeviceByDeviceSn(String deviceSn){
        return xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
    }

    public int saveDevcieGridProduct(String index,String deviceSn,String stateType){
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        XwDevice xwDevice1=new XwDevice();
        xwDevice1.setDeviceId(xwDevice.getDeviceId());
        if(index!=null&&index.equals("0")){
            xwDevice1.setGrid01StateType(stateType);
        }else if(index!=null&&index.equals("1")){
            xwDevice1.setGrid02StateType(stateType);
        }else if(index!=null&&index.equals("2")){
            xwDevice1.setGrid03StateType(stateType);
        }else if(index!=null&&index.equals("3")){
            xwDevice1.setGrid04StateType(stateType);
        }else if(index!=null&&index.equals("4")){
            xwDevice1.setGrid05StateType(stateType);
        }else if(index!=null&&index.equals("5")){
            xwDevice1.setGrid06StateType(stateType);
        }
        return xwDeviceMapper.updateXwDevice(xwDevice1);
    }

    public int saveDevcieRepairFlag(String deviceSn,String repairFlag){
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        xwDevice.setRepairFlag(repairFlag);
        return xwDeviceMapper.updateXwDevice(xwDevice);
    }

    public int saveDeviceBallBuyState(String deviceSn,int index){
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        String stateType="2";
        if(index==1){
            xwDevice.setGrid01StateType(stateType);
        }else if(index==2){
            xwDevice.setGrid02StateType(stateType);
        }else if(index==3){
            xwDevice.setGrid03StateType(stateType);
        }else if(index==4){
            xwDevice.setGrid04StateType(stateType);
        }else if(index==5){
            xwDevice.setGrid05StateType(stateType);
        }else if(index==6){
            xwDevice.setGrid06StateType(stateType);
        }
        xwDevice.setRepairFlag("Y");
        return xwDeviceMapper.updateXwDevice(xwDevice);
    }

    public int unBingDeviceState(String deviceSn,String type,String openId){
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        if(type.equals("1")){
                if(openId.equals(xwDevice.getAgentOpenId())){
                    xwDevice.setAgentOpenId("");
                    return xwDeviceMapper.updateXwDevice(xwDevice);
                }
        }else{
            if(openId.equals(xwDevice.getEnduserOpenId())){
                xwDevice.setEnduserOpenId("");
                return xwDeviceMapper.updateXwDevice(xwDevice);
            }
        }
        return 2;
    }
    public List<XwDevice> getRepairList(String openId){
        return xwDeviceMapper.selectRepairXwDeviceListByOpenId(openId);
    }
    public int saveDeviceAddress(String deviceSn,String deviceAddress){
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        xwDevice.setDeviceAddress(deviceAddress);
        return xwDeviceMapper.updateXwDevice(xwDevice);
    }

    public int checkDeviceForReplenishment(String deviceSn,String openId){
        List<XwDevice> xwDeviceList=xwDeviceMapper.checkDeviceForReplenishment(deviceSn,openId);
        if(xwDeviceList!=null&&xwDeviceList.size()>0){
            return 1;
        }else{
            return 0;
        }
    }
    public List<XwDevice> getAllDownloadBatch(){
        return xwDeviceMapper.getAllDownloadBatch();
    }




    public byte[] downLoadFile(String downloadBatch) throws Exception{
        List<XwDevice> xwDeviceList=xwDeviceMapper.getByDownloadBatch(downloadBatch);
        ZipOutputStream zip=null;
        String zipOutputPath =RuoYiConfig.getProfile()+"/"+downloadBatch+".zip";
        File f = new File(zipOutputPath);
        byte[] res=null;
        if(f.exists()){
            res= Files.readAllBytes(Paths.get(zipOutputPath));
            return res;
        }
        try{
            FileOutputStream fos = new FileOutputStream(zipOutputPath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            String deviceSnStr="";
            String snFile=RuoYiConfig.getProfile()+"/"+downloadBatch+"_sn.txt";
            FileWriter fw = new FileWriter(snFile);
            BufferedWriter bw = new BufferedWriter(fw);
            for(int i=0;i<xwDeviceList.size();i++){
                String deviceSn=xwDeviceList.get(i).getDeviceSn();
                String env_version="release";
                String filePath = RuoYiConfig.getProfile()+"/"+deviceSn+"_"+env_version+"_sn.png";
                String filename=deviceSn+"_"+env_version+"_sn.png";
                wxWechatTools.getQRCode(null,deviceSn,env_version);
                addFileToZip(zos, filePath, filename);
                bw.write(deviceSn+",");
                bw.newLine();
            }
            bw.close();
            addFileToZip(zos, snFile, downloadBatch+"_sn.txt");
            zos.close();
            fos.close();

            res= Files.readAllBytes(Paths.get(zipOutputPath));
            return res;
        }catch (Exception e){
            throw e;
        }finally {
            //zip.close();
            //outputStream.close();
        }
    }
    private void addFileToZip(ZipOutputStream zos, String filePath, String fileName) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }

    public static void main(String args[])throws Exception{
      String zipFile="D:/ruoyi/uploadPath/test.zip";
      String file1="D:\\ruoyi\\uploadPath\\33889896_release.jpg";
      String file2="D:\\ruoyi\\uploadPath\\33889896_release_sn.png";
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        addFileToZipNew(zos, file1, "name_in_zip.png");
        addFileToZipNew(zos, file2, "name_in_zip2.png");
        zos.close();
        fos.close();
        System.out.println("Files have been successfully compressed!");

}
    private static void addFileToZipNew(ZipOutputStream zos, String filePath, String fileName) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}
